import 'dart:io';

import 'package:dio/dio.dart' as d;
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:jump_scape/js_data/js_box/js_member.dart';
import 'package:jump_scape/js_data/js_http/js_http.dart';
import 'package:language_code/language_code.dart';
import 'package:path_provider/path_provider.dart';

import '../js_config.dart';
import '../objectbox.g.dart';
import 'js_box/js_init.dart';
import 'js_model/js_oss.dart';

class JsMember {
  Future<bool> synchronizationMember({
    required Function(MemberBox member) onSuccess,
    required Function(String msg) onFailed,
  }) async {
    final userId = (await JsObjectBox.setting).userId;
    final body = await JsHttp.get(JsApp.jsHttpMember, {'userId': userId});
    bool isSucc = body[1];
    if (isSucc) {
      final Map<String, dynamic> userInfo = body[2];

      final memberOld = JsObjectBox.memberBox.query(MemberBox_.userId.equals(userId)).build().findFirst();
      if (memberOld != null) {
        memberOld.userId = userId; // 用户ID
        memberOld.name = userInfo['nickname'].toString(); // 昵称
        memberOld.avatarUrl = userInfo['avatarUrl'].toString(); // 头像
        memberOld.balance = userInfo['availableCoins'].toString(); // 剩余金币个数
        memberOld.birth = DateTime.parse(userInfo['birthday'].toString()); // 生日 1995-01-01
        memberOld.country = userInfo['country'].toString(); // 国家
        JsObjectBox.memberBox.put(memberOld);

        debugPrint('[member] ✅ $memberOld');

        onSuccess(memberOld);
      } else {
        final memberNew = MemberBox.create(
          userId: userId, // 用户ID
          name: userInfo['nickname'].toString(), // 昵称
          avatarUrl: userInfo['avatarUrl'].toString(), // 头像
          balance: userInfo['availableCoins'].toString(), // 剩余金币个数
          birth: DateTime.parse(userInfo['birthday'].toString()), // 生日 1995-01-01
          country: userInfo['country'].toString(), // 国家
        );
        memberNew.id = JsObjectBox.memberBox.put(memberNew);

        debugPrint('[member] ✅ $memberNew');

        onSuccess(memberNew);
      }

      return true;
    } else {
      final memberOld = JsObjectBox.memberBox.query(MemberBox_.userId.equals(userId)).build().findFirst();
      if (memberOld != null) {
        onSuccess(memberOld);
        return true;
      } else {
        onFailed(body[2]);
        return false;
      }
    }
  }

  Future<void> saveMember({
    required String avatarUrl,
    required String nickname,
    required DateTime? birthday,
    required String country,
    required Function(MemberBox member) onSuccess,
    required Function(String msg) onFailed,
  }) async {
    final language = LanguageCode.code.code;

    await _uploadMemberAvatar(avatarUrl);
    await JsHttp.post(JsApp.jsHttpSaveMember, true, {
      'nickname': nickname,
      'birthday': birthday == null ? '1995-01-01' : '${birthday.year}-${birthday.month < 9 ? '0${birthday.month}' : birthday.month}-${birthday.day < 9 ? '0${birthday.day}' : birthday.day}',
      'country': country,
      'language': language,
    });

    await synchronizationMember(onSuccess: onSuccess, onFailed: onFailed);
  }

  Future<void> _uploadMemberAvatar(String avatarUrl) async {
    if (avatarUrl.isEmpty || avatarUrl.startsWith('http')) return;

    final File file;
    if (avatarUrl.startsWith('assets')) {
      // 从 assets 文件夹加载文件
      final byteData = await rootBundle.load(avatarUrl);
      // Step 2: 获取临时目录并保存文件
      final tempDir = await getTemporaryDirectory();
      file = File('${tempDir.path}/jump_scape_normal_avatar.png');
      await file.writeAsBytes(byteData.buffer.asUint8List());
    } else {
      file = File(avatarUrl);
    }

    final ossBody = await JsHttp.get(JsApp.jsHttpOSS);

    bool isSucc = ossBody[1];
    if (isSucc) {
      final ossModel = JsOss.fromMap(ossBody[2]);

      DateTime dateTime = DateTime.now();
      String fileName = file.path.split('/').last;
      String format = fileName.split('.').last;
      int imageTimeName = dateTime.millisecondsSinceEpoch + (dateTime.microsecondsSinceEpoch ~/ 1000000);
      String imageName = '$imageTimeName.$format';
      String host = ossModel.host;
      String dir = ossModel.dir;

      var filePath = await d.MultipartFile.fromFile(file.path, filename: fileName);
      final formData = d.FormData.fromMap({
        'ossaccessKeyId': ossModel.accessKeyId,
        'policy': ossModel.policy,
        'signature': ossModel.signature,
        'callback': ossModel.callback,
        'key': '$dir/$imageName',
        'file': filePath,
      });
      d.Dio dio = d.Dio();
      var response = await dio.post(host, data: formData);

      if (response.data != null) {
        final filename = response.data['data']['filename'];
        if (filename != null) {
          await JsHttp.post(JsApp.jsHttpUpdateAvatar, true, {'avatarPath': filename.toString()});
        }
      }
    }
  }
}
